import { useState, useCallback, useRef, useEffect } from 'react';
import { App } from 'antd';

interface PaginationState {
  current: number;
  pageSize: number;
  total: number;
}

interface UseCrudListOptions<T, P> {
  fetchApi: (params: P & { page: number; pageSize: number }) => Promise<any>;
  initialPageSize?: number;
  autoLoad?: boolean; // 是否自动加载数据，默认为 true
  onError?: (error: any) => void;
}

interface UseCrudListReturn<T, P> {
  // 数据状态
  data: T[];
  loading: boolean;
  pagination: PaginationState;
  searchParams: P;
  
  // 操作方法
  fetchData: (params?: Partial<P & { page?: number; pageSize?: number }>) => Promise<void>;
  handleSearch: (values: P) => void;
  handleReset: () => void;
  handlePageChange: (page: number, pageSize: number) => void;
  refresh: () => void;
}

/**
 * 统一的 CRUD 列表 Hook
 * @param options 配置选项
 * @returns 列表状态和操作方法
 */
export function useCrudList<T = any, P extends Record<string, any> = any>(
  options: UseCrudListOptions<T, P>
): UseCrudListReturn<T, P> {
  const { fetchApi, initialPageSize = 20, autoLoad = true, onError } = options;
  const { message } = App.useApp();

  const [data, setData] = useState<T[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState<PaginationState>({
    current: 1,
    pageSize: initialPageSize,
    total: 0,
  });
  const [searchParams, setSearchParams] = useState<P>({} as P);

  // 使用 ref 保存最新的 pagination 和 searchParams
  const paginationRef = useRef(pagination);
  const searchParamsRef = useRef(searchParams);

  useEffect(() => {
    paginationRef.current = pagination;
  }, [pagination]);

  useEffect(() => {
    searchParamsRef.current = searchParams;
  }, [searchParams]);

  /**
   * 获取数据
   */
  const fetchData = useCallback(
    async (params?: Partial<P & { page?: number; pageSize?: number }>) => {
      setLoading(true);
      try {
        // 使用 ref 获取最新的 pagination 和 searchParams
        const currentPagination = paginationRef.current;
        const currentSearchParams = searchParamsRef.current;

        // 构建请求参数，只包含 page、pageSize 和搜索参数
        const requestParams = {
          ...currentSearchParams,
          page: params?.page !== undefined ? params.page : currentPagination.current,
          pageSize: params?.pageSize !== undefined ? params.pageSize : currentPagination.pageSize,
          ...params,
        } as P & { page: number; pageSize: number };

        // 移除 undefined 值
        Object.keys(requestParams).forEach(key => {
          if (requestParams[key] === undefined) {
            delete requestParams[key];
          }
        });

        const response = await fetchApi(requestParams);

        if (response.data.success) {
          setData(response.data.data || []);
          
          // 更新分页信息
          if (response.data.pagination) {
            setPagination({
              current: response.data.pagination.page || currentPagination.current,
              pageSize: response.data.pagination.pageSize || currentPagination.pageSize,
              total: response.data.pagination.total || 0,
            });
          }
        }
      } catch (error: any) {
        console.error('❌ Failed to fetch data:', error);
        if (onError) {
          onError(error);
        } else {
          message.error(error.response?.data?.message || '获取数据失败');
        }
      } finally {
        setLoading(false);
      }
    },
    [fetchApi, onError]
  );

  /**
   * 搜索
   */
  const handleSearch = useCallback(
    (values: P) => {
      setSearchParams(values);
      setPagination(prev => ({ ...prev, current: 1 }));
      // 使用 ref 获取当前 pageSize
      fetchData({ ...values, page: 1, pageSize: paginationRef.current.pageSize } as Partial<P & { page?: number; pageSize?: number }>);
    },
    [fetchData]
  );

  /**
   * 重置搜索
   */
  const handleReset = useCallback(() => {
    setSearchParams({} as P);
    setPagination(prev => ({ ...prev, current: 1 }));
    // 使用 ref 获取当前 pageSize
    fetchData({ page: 1, pageSize: paginationRef.current.pageSize } as Partial<P & { page?: number; pageSize?: number }>);
  }, [fetchData]);

  /**
   * 分页变化
   */
  const handlePageChange = useCallback(
    (page: number, pageSize: number) => {
      fetchData({ page, pageSize } as Partial<P & { page?: number; pageSize?: number }>);
    },
    [fetchData]
  );

  /**
   * 刷新当前页
   */
  const refresh = useCallback(() => {
    fetchData();
  }, [fetchData]);

  /**
   * 初始加载数据
   */
  useEffect(() => {
    if (autoLoad) {
      fetchData();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // 只在组件挂载时执行一次

  return {
    data,
    loading,
    pagination,
    searchParams,
    fetchData,
    handleSearch,
    handleReset,
    handlePageChange,
    refresh,
  };
}

